package debtbundler.presentation;

import java.awt.Container;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.SwingWorker;

import debtbundler.domain.bll.solver.ClosestMatchSolver;
import debtbundler.domain.entity.Debt;
import debtbundler.domain.entity.Person;
import debtbundler.presentation.debtviewer.DebtViewer;

/**
 * A background task that calculates debts for the specified persons
 * and when done, adds a {@link DebtViewer} in the specified component.
 * The component can be visible before starting this task.
 * 
 * @author Anssi
 *
 */
public class SolverTask extends SwingWorker<DebtViewer, Void> {
	
	private static Logger logger = Logger.getLogger(SolverTask.class.getName()); 
	
	private Collection<Person> persons;
	private Container container;
	
	public SolverTask(Collection<Person> persons, Container container) {
		this.persons = persons;
		this.container = container;
	}

	@Override
	protected DebtViewer doInBackground() throws Exception {
		ClosestMatchSolver solver = new ClosestMatchSolver(persons);
		Collection<Debt> debts = solver.getDebts();
		
		DebtViewer viewer = new DebtViewer(debts);
		return viewer;
	}
	
    @Override
    protected void done() {
        try {
			DebtViewer viewer = get();
			container.add(viewer);
			container.validate();
		} catch (Exception e) {
			logger.log(Level.SEVERE, "Error when calculating debts", e);
			RuntimeException ex = new RuntimeException(e);
			throw ex;
		} 
		
    }


}
